package com.haizhi.workstation.service.impl;

import com.alibaba.fastjson.JSON;
import com.haizhi.workstation.exception.GlobalException;
import com.haizhi.workstation.mq.AppOperationMessage;
import com.haizhi.workstation.service.PublicSecurityService;
import com.haizhi.workstation.util.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class PublicSecurityServiceImpl implements PublicSecurityService {
    @Autowired
    private Constants constants;

    @Value("${public.dataFileUrlPrefix}")
    private String dataFileUrlPrefix;
    @Override
    public void createFileForSend(AppOperationMessage appOperationMessage) {
        String requestUrl = appOperationMessage.getRequestUrl();
        //String key = appOperationMessage.getKey();

        String params = appOperationMessage.getParams();

        String data = appOperationMessage.getDataFileUrlOrData();
        if(StringUtils.hasLength(data) && data.startsWith(dataFileUrlPrefix)){
            File file = new File(data);
            data = JSONUtil.getDataFromFile(file);

            FileUtils.fileRemove(file);//删除文件
        }


        String appId = appOperationMessage.getAppId();
        String responseUrl = appOperationMessage.getResponseUrl();
        StringBuilder sb = new StringBuilder(200);

        sb.append("[{'key'").append(":'");
        StringBuilder headerContent = new StringBuilder(200);
        if(StringUtils.hasLength(requestUrl)){
            headerContent.append("{\"requestUrl\"").append(":\"").append(requestUrl).append("\",");
        }
        if(StringUtils.hasLength(responseUrl)){
            headerContent.append("\"responseUrl\"").append(":\"").append(responseUrl).append("\",");
        }
        if(StringUtils.hasLength(appId)){
            headerContent.append("\"appId\"").append(":\"").append(appId).append("\",");
        }
        headerContent.append("\"params\"").append(":'").append(params).append("'}");

        try {
//            String seed = "haiZhiAnd360ForImageToPublicSecurity";//种子
//
//            //System.out.println("原文：\n" + headerContent.toString());
//            Map<String, Object> keyMap = RSAUtil.initKey(seed);//初始化密钥
//            String publicKey = RSAUtil.getPublicKey(keyMap);//公钥
//            String privateKey = RSAUtil.getPrivateKey(keyMap);//私钥
//            System.out.println("公钥：\n" + publicKey);
//            System.out.println("私钥：\n" + privateKey);
           // String encodedStr = RSAUtil.encryptByPublicKey(headerContent.toString(), publicKey);//加密
            String encodedStr = RSAUtil.encryptByPublicKey(headerContent.toString(), Constants.PUBLIC_KEY);//加密
            //System.out.println("密文：\n" + encodedStr);
            log.info("\n密文====={}",encodedStr);

            String decodedStr = RSAUtil.decryptByPrivateKey(encodedStr, Constants.PRIVATE_KEY);//解密
            log.info("解密后的结果======\n{}" + decodedStr);
            sb.append(encodedStr).append("',");
        }catch (Exception e){
            e.printStackTrace();
        }
        sb.append("'data'").append(":'").append(data).append("'}]");
        //将文件写到ftp的send
        JSONUtil.saveDataToFile(constants.PUBLIC_SEND_FOLDER+appOperationMessage.getDataUrl().replace("/","-"),sb.toString());

        //文件备份
        log.info("备份文件："+constants.PUBLIC_SEND_FOLDER_BACKUPS+appOperationMessage.getDataUrl().replace("/","-"));
        JSONUtil.saveDataToFile(constants.PUBLIC_SEND_FOLDER_BACKUPS+appOperationMessage.getDataUrl().replace("/","-"),sb.toString());
        //send中文件备份
//        JSONUtil.saveDataToFile(Constants.SEND_FOLDER_BACKUPS+appOperationMessage.getDataUrl(),sb.toString());
    }

    @Override
    public void dealFile(String JsonContext, String fileName) {
        //public的receive文件备份
        log.info("fileName====={}",fileName);
        log.info("JsonContext====={}",JsonContext);
        JSONUtil.saveDataToFile(constants.PUBLIC_RECEIVE_FOLDER_BACKUPS+fileName,JsonContext);
        JSONArray jsonArray = null;
        try {
            jsonArray = JSONArray.fromObject(JsonContext);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        int size = jsonArray.size();
        if(jsonArray==null){
            log.info("非法文件：{}",fileName);
            return;
        }
        log.info("Size: {}", size);
        for(int  i = 0; i < size; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            try {
                String keyContent = RSAUtil.decryptByPrivateKey(jsonObject.get("key")+"", Constants.PRIVATE_KEY);//解密
                log.info("加密文件的文件头====={}",keyContent);
                com.alibaba.fastjson.JSONObject jsonObject1 = JSON.parseObject(keyContent);
                String requestUrl = (String)jsonObject1.get("requestUrl");
                String responseUrl = (String)jsonObject1.get("responseUrl");
                String appId = (String)jsonObject1.get("appId");

                //String appId = (String)jsonObject1.get("appId");

                String params = (String)jsonObject1.get("params");
                log.info("params:{}",params);
                String data = jsonObject.get("data") + "";
                log.info("data:{}",data);
                //回调时传的参数
                //String requestParam = "";
                if(!StringUtils.hasLength(responseUrl) || !StringUtils.hasLength(requestUrl)){
                    log.info("requestUrl Or responseUrl is Empty");
                    log.info("requestUrl====={}",requestUrl);
//                    throw new GlobalException(CodeMsg.ERR_OPERATION);
                }
                //requestParam = requestParam+"responseUrl="+responseUrl;
                /*if(!StringUtils.hasLength(params) *//*|| !StringUtils.hasLength(appId)*//*){
                    throw new GlobalException(CodeMsg.ERR_OPERATION);
                }*/
                //old改动
//                params = URLEncoder.encode(params, "utf-8");
//                requestParam = requestParam+"params="+params;
//                if(StringUtils.hasLength(data)){
//                    //将data数据作为参数拼接到参数中
//                    //data = URLEncoder.encode(data, "utf-8");
//                    requestParam = requestParam+"&data="+data;
//                    log.info("requestParam: {}",requestParam);
//                }
//                if(StringUtils.hasLength(appId)){
//                    //requestParam = requestParam+"&appId="+appId;
//                }
                //解析出responseUrl并回调
                log.info("responseUrl===== {}",responseUrl);
                log.info("requestUrl===== {}",requestUrl);
//                log.info("requestParam===== {}",requestParam);

                //解析receive文件requestUrl，去访问

                //新改动
                Map<String,String> paramMaps = new HashMap<>();
                paramMaps.put("params",params);
                paramMaps.put("data",data);
                paramMaps.put("responseUrl",responseUrl);
                HttpClientUtils.doPost(requestUrl,paramMaps);


            } catch (GlobalException e) {
                throw e;
            }catch (Exception e) {
                log.error("错误文件："+constants.PUBLIC_RECEIVE_FOLDER_BACKUPS+fileName);
                e.printStackTrace();
            }
            System.out.println("[" + i + "]data=" + jsonObject.get("data"));
        }

        System.out.println("[新建]:" + fileName);
    }
}
